package edge.display.backend.MsgReceiver.Mqtt;

import edge.display.backend.MsgDistributer.WebSocket.WebSocketServer;
import edge.display.backend.MsgHandler.QHandler;
import org.eclipse.paho.client.mqttv3.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;
import org.springframework.stereotype.Component;

import java.util.logging.Logger;

@Component
@Configuration
public class MqttReceiver {
    private static MqttClient mqttclient;
    @Value("${mqtt.taskTopic}")
    public String taskTopic;
    @Value("${mqtt.offloadTopic}")
    public String offloadTopic;
    @Value("${mqtt.resultTopic}")
    public String resultTopic;
    @Value("${mqtt.host}")
    String mqttHost;
    @Value("${mqtt.clientId}")
    String clientId;
    @Autowired
    WebSocketServer webSocketServer;
    Logger logger = Logger.getLogger(MqttReceiver.class.getName());

    public void getConnectionMqtt() {
        if (mqttclient == null) {
            MqttClient client = null;
            try {
                client = new MqttClient(mqttHost, clientId);
                MqttConnectOptions connOpts = new MqttConnectOptions();
                connOpts.setCleanSession(true);
                System.out.println("[MQTT] Connecting to broker: " + mqttHost);
                connOpts.setConnectionTimeout(10);
                connOpts.setKeepAliveInterval(20);
                client.setCallback(new MqttCallback() {

                    @Override
                    public void connectionLost(Throwable throwable) {

                    }

                    @Override
                    // s为topic，mqttMessage为payloadString
                    public void messageArrived(String s, MqttMessage mqttMessage) {
                        QHandler.handle(mqttMessage.toString());
                    }

                    @Override
                    public void deliveryComplete(IMqttDeliveryToken iMqttDeliveryToken) {

                    }
                });
                client.connect(connOpts);

            } catch (MqttException e) {
                e.printStackTrace();
            }
            mqttclient = client;
        }
    }

    public void subtopic(String topic) throws MqttException {
        mqttclient.subscribe(topic);
    }

    public void subAll() throws MqttException {
        mqttclient.subscribe(taskTopic);
        mqttclient.subscribe(offloadTopic);
        mqttclient.subscribe(resultTopic);
    }

}
